<template>
  <div class="chart-container">
    <div id="multi-line-chart" style="height: 100%; width: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "DataBoard",
  data() {
    return {
      chartInstance: null,
      chartOptions: null,
      latestDate: null,
      timeRange: []
    }
  },
  methods: {
    getLatestTimeDay() {
      this.$axios.get(this.$httpUrlVisualization + '/getLatestTimeDay').then(res => {
        res = res.data;
        if (res.code === 200) {
          this.latestDate = res.data.latestTime_day;
          sessionStorage.setItem('latestTime_day',this.latestDate)
          this.calculateTimeRange();
          this.initChart();
          this.loadChartData();
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    calculateTimeRange() {
      const latest = new Date(this.latestDate);
      const pastDate = new Date(latest);
      pastDate.setDate(latest.getDate() - 10);

      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      this.timeRange = [
        formatDate(pastDate),
        formatDate(latest)
      ];
    },

    initChart() {
      this.chartInstance = echarts.init(document.getElementById('multi-line-chart'));

      this.chartOptions = {
        tooltip: {
          trigger: 'axis',
          confine: true
        },
        legend: {
          data: ['产量值', '总焦比值', 'BV(风量)', '匹配模式'],
          top: '0%',

        },
        grid: [
          {
            left: '12%',
            right: '3%',
            top: '8%',
            height: '15%'
          },
          {
            left: '12%',
            right: '3%',
            top: '30%',
            height: '15%'
          },
          {
            left: '12%',
            right: '3%',
            top: '52%',
            height: '15%'
          },
          {
            left: '12%',
            right: '3%',
            top: '75%', // 调整位置确保不超出容器
            height: '15%'
          }
        ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: false },
            show: false,
            gridIndex: 0
          },
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: false },
            show: false,
            gridIndex: 1
          },
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: false },
            gridIndex: 2,
            show: false,
            axisLabel: {
              rotate: 30,
              interval: 'auto'
            }
          },
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: false },
            gridIndex: 3,
            axisLabel: {
              rotate: 35,
              interval: 'auto'
            }
          }
        ],
        yAxis: [
          {
            name: '产量值 t/d',
            type: 'value',
            gridIndex: 0
          },
          {
            name: '总焦比 kg/t',
            type: 'value',
            gridIndex: 1
          },
          {
            name: '风量 m^3/min',
            type: 'value',
            gridIndex: 2,
          },
          {
            name: '匹配模式',
            type: 'category',
            gridIndex: 3,
            axisLabel: {
              formatter: function(value) {
                return value; // Display the string as is
              }
            }
          }
        ],
        series: [
          {
            name: '产量值',
            type: 'line',
            xAxisIndex: 0,
            yAxisIndex: 0,
            symbol: 'circle',
            symbolSize: 6,
            smooth: true,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.1
            }
          },
          {
            name: '总焦比值',
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            symbol: 'circle',
            symbolSize: 6,
            smooth: true,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.1
            }
          },
          {
            name: 'BV(风量)',
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2,
            symbol: 'circle',
            symbolSize: 6,
            smooth: true,
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.1
            }
          },
          {
            name: '匹配模式',
            type: 'effectScatter',
            xAxisIndex: 3,
            yAxisIndex: 3,
            symbol: 'circle',
            symbolSize: 15,
            itemStyle: {
              color: '#74a3ea'
            },
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                return params.data; // Display the string value
              }
            }
          }
        ]
      };

      this.chartInstance.setOption(this.chartOptions);
    },

    loadChartData() {
      const input = {
        startTime: this.timeRange[0],
        endTime: this.timeRange[1],
        parameters: ['1001', '1006', '1010']
      };

      this.$axios.post(this.$httpUrlVisualization + '/getParallelData', input).then(res => {
        res = res.data;
        if (res.code === 200) {
          const xData = res.data.XData;
          const seriesData = res.data.seriesData;

          // Example status data (you would replace this with your actual data)
          // const statusData = ['A1','A1','A1','A1','A1','A1','A1','A1','A1','A2'];
          const statusData = ['A1','A1','A1','A1','A1','A1','A1','A1','A1','A2'];


          // Update chart options with new data
          this.chartOptions.xAxis[0].data = xData;
          this.chartOptions.xAxis[1].data = xData;
          this.chartOptions.xAxis[2].data = xData;
          this.chartOptions.xAxis[3].data = xData;

          this.chartOptions.series[0].data = seriesData['产量'] || [];
          this.chartOptions.series[1].data = seriesData['总焦比'] || [];
          this.chartOptions.series[2].data = seriesData['BV（风量）'] || [];
          this.chartOptions.series[3].data = statusData;

          this.chartInstance.setOption(this.chartOptions);
        } else {
          this.$message.error(res.msg);
        }
      });

      const intput = {
        recordTimes:[this.latestDate], // Initialize empty
        clusterAlgorithm:'GMM',
        isday: false
      };

      this.$axios.post(this.$Python+'/getTenDaysPredict',intput).then(res => {
        if(res.data.code === 200 && res.data.data){
          this.chartOptions.series[3].data = res.data.data || [];
          this.chartInstance.setOption(this.chartOptions);
        }else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => {
        console.error("Error fetching TenDays prediction data:", err);
      })
    },

    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  },
  mounted() {
    this.getLatestTimeDay();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 600px; /* Increased to accommodate the new grid */
  padding: 10px;
  box-sizing: border-box;
}
</style>
